以下是取自企業意見調查網站的例子,Python 程式碼建立了新的 Business 物件並依序設定了name、url 及date_created:
business = Business()
business.name = request.POST["name"]
url_path_name = business.name.lower()
url_path_name = re.sub(r"['\.]","",url_path_name)
url_path_name = re.sub(r"['^a-z0-9]+","-",url_path_name)
url_path_name = url_path_name.strip("-")
business.url = "/biz/" + url_path_name
business.date_created = datetime.datetime.utcnow()
business.save_to_database()
這段程式碼中不相關的子問題是:「將名稱轉換為合法 URL 」,能夠輕易抽離這段程式碼,這麼做之後甚至可以預先編譯好正規表示式(並給予比較好讀的名稱):
CHARS_TO_REMOVE = re.compile(r"['\.]+")
CHARS_TO_DASH = re.compile(r"['^a-z0-9]")
def make_url_friendly(text):
text = text.lower()
text = CHARS_TO_REMOVE.sub('',text)
text = CHARS_TO_DASH.sub('-',text)
return text.strip("-")
現在原先的程式碼有更加「一致」的模式:
business = Business()
business.name = request.POST["name"]
business.url = "/biz/" + make_url_friend(business.name)
business.date_created = datetime.datetime.utcnow()
business.save_to_database
程式碼讀起來更省力,不再被使用正規表示式的字串處理細節而干擾。